/*
 * @Author: zhangyang
 * @Date: 2022-06-22 15:55:28
 * @LastEditTime: 2022-06-23 18:51:25
 * @Description:
 */
import { useContext } from '@modern-js/runtime/server';
import md5 from 'md5';

export const post = async () => {
  const ctx = useContext();

  ctx.logger.info(ctx.request.body);
  const { username, password } = ctx.request.body;

  if (!username || !password) {
    return ctx.helper.fail({
      msg: '缺乏关键参数',
    });
  }

  const user = await ctx.service.user.findOne({
    username,
  });

  if (user) {
    if (md5(`${ctx.app.config._young.key}${password}`) === user.password) {
      const jwt = ctx.helper.generateToken({
        username,
        password,
        nickname: user.nickname,
      });
      return ctx.helper.success({
        data: jwt,
        msg: '登录成功！',
      });
    } else {
      return ctx.helper.fail({
        msg: '用户名或密码错误！',
      });
    }
  } else {
    return ctx.helper.fail({
      msg: '用户名不存在！',
    });
  }
};
